<template>
  <div class="order-management">
    <PageLayout>


      <template #search>
        <n-collapse>
          <n-collapse-item name="1">
            <div class="compact-search-container">
              <n-form inline :model="searchForm" label-placement="left" class="compact-search-form">

                <n-form-item label="订单号">
                  <n-input v-model:value="searchForm.orderId" placeholder="订单号" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="下单人姓名">
                  <n-input v-model:value="searchForm.orderByUserName" placeholder="下单人姓名" clearable
                    class="compact-input" size="large" />
                </n-form-item>

                <n-form-item label="下单人电话">
                  <n-input v-model:value="searchForm.orderByUserTel" placeholder="下单人电话" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="订单状态">
                  <n-select v-model:value="searchForm.orderType" placeholder="订单状态" :options="statusOptions" clearable
                    class="compact-select" size="large" />
                </n-form-item>

                <n-form-item label="订单名称">
                  <n-input v-model:value="searchForm.orderName" placeholder="订单名称" clearable class="compact-input"
                    size="large" />
                </n-form-item>

                <n-form-item label="订单商品ID">
                  <n-input v-model:value="searchForm.orderProductId" placeholder="订单商品ID" clearable
                    class="compact-input" size="large" />
                </n-form-item>

                <n-form-item label="订单描述">
                  <n-input v-model:value="searchForm.orderDes" placeholder="订单描述" clearable class="compact-input"
                    size="large" />
                </n-form-item>



                <n-form-item>
                  <n-space size="large">
                    <n-button type="primary" @click="handleSearch" size="large" class="compact-btn">
                      <template #icon>
                        <n-icon>
                          <SearchOutline />
                        </n-icon>
                      </template>
                      搜索
                    </n-button>
                    <n-button @click="handleReset" size="large" class="compact-btn">
                      <template #icon>
                        <n-icon>
                          <RefreshOutline />
                        </n-icon>
                      </template>
                      重置
                    </n-button>

                    <!-- <n-button type="warning" @click="testAPI" size="small" class="compact-btn">
                  <template #icon>
                    <n-icon>
                      <SearchOutline />
                    </n-icon>
                  </template>
                  测试API
                </n-button> -->

                  </n-space>
                </n-form-item>
              </n-form>
            </div>
            <template #header>
              <n-text type="info">
                <span style="font-size: 15px;font-weight: 700;">搜索表单</span>
              </n-text>
            </template>
            <template #header-extra>
              <n-text type="info">
                <span style="color: coral;">只有订单号和订单商品ID不支持模糊查询</span>
              </n-text>
            </template>
          </n-collapse-item>
        </n-collapse>
      </template>

      <!-- 表格头部 -->
      <template #header>
        <div class="compact-table-header">
          <n-button type="primary" @click="handleAdd" class="compact-add-btn" size="large">
            <template #icon>
              <n-icon>
                <AddOutline />
              </n-icon>
            </template>
            新增订单
          </n-button>
          <n-button type="info" @click="handleRefresh" class="compact-add-btn" size="large">
            <template #icon>
              <n-icon>
                <RefreshOutline />
              </n-icon>
            </template>
            刷新数据
          </n-button>
        </div>
      </template>

      <!-- 表格内容 -->
      <template #table>
        <n-data-table :columns="columns" :data="tableData" :loading="loading" :single-line="false" :scroll-x="3000"
          :flex-height="true" class="data-table" striped :row-key="(row) => row.orderId"
          :checked-row-keys="checkedRowKeys" @update:checked-row-keys="handleCheckedRowKeysChange"
          :row-class-name="getRowClassName" @row-click="handleRowClick" />
      </template>

      <!-- 分页 -->
      <template #pagination>
        <n-pagination v-model:page="pagination.page" v-model:page-size="pagination.pageSize"
          :item-count="pagination.itemCount" :page-sizes="[10, 20, 50, 100, 200]" show-size-picker show-quick-jumper
          :prefix="paginationPrefix" @update:page="handlePageChange" @update:page-size="handlePageSizeChange" />
      </template>
    </PageLayout>




    <!-- 新增订单 -->
    <n-modal v-model:show="showOrderModal" :mask-closable="false" preset="card" :title="modalTitle" class="modern-modal"
      :style="{ width: '800px' }" :auto-focus="false" :close-on-esc="false" transform-origin="center">

      <template #header>
        <div class="modal-header">
          <div class="modal-title-wrapper">
            <n-icon size="24" class="modal-icon">
              <AddOutline v-if="modalMode === 'add'" />
              <CreateOutline v-else-if="modalMode === 'edit'" />
              <EyeOutline v-else />
            </n-icon>
            <div class="modal-title-text">
              <h3>{{ modalTitle }}</h3>
              <p class="modal-subtitle">{{ modalMode === 'add' ? '创建新的订单记录' : modalMode === 'edit' ? '修改订单信息' : '查看订单详情'
                }}</p>
            </div>
          </div>
        </div>
      </template>

      <template #default>
        <div class="modal-content">
          <n-form ref="orderFormRef" :model="orderForm" :rules="orderFormRules" label-placement="top"
            class="modern-form" :disabled="modalMode === 'view'">
            <div class="form-grid">
              <div class="form-section">
                <h4 class="section-title">客户信息</h4>
                <div class="form-row">

                  <n-form-item label="客户ID" path="orderByUser" class="form-item">
                    <n-input v-model:value="orderForm.orderByUser" placeholder="请输入下单人ID" class="modern-input"
                      :disabled="modalMode === 'view'" @blur="getUserInfoById" />
                  </n-form-item>
                  <n-form-item label="客户账号" path="orderByUserName" class="form-item">
                    <n-input v-model:value="orderForm.orderByUserName" placeholder="请输下单人账号" class="modern-input"
                      :disabled="modalMode === 'view'" @blur="getUserInfoById" />
                  </n-form-item>
                  <n-form-item label="客户电话" path="orderByUserTel" class="form-item">
                    <n-input v-model:value="orderForm.orderByUserTel" placeholder="请输入下单人电话" class="modern-input"
                      disabled @blur="getUserInfoById" />
                  </n-form-item>

                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">商品信息</h4>
                <div class="form-row">

                  <n-form-item label="商品ID" path="orderProductId" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderProductId" placeholder="请输入商品ID" class="modern-input"
                      :disabled="modalMode === 'view'" @blur="getProductById" />
                  </n-form-item>

                  <n-form-item label="商品名称" path="orderProductName" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderProductName" placeholder="请输入商品名称" class="modern-input"
                      :disabled="modalMode === 'view'" @blur="getProductById" />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="商品图片链接" path="orderProductImg" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderProductImg" placeholder="请输入商品图片链接" class="modern-input"
                      disabled />
                  </n-form-item>

                  <n-form-item label="商品单价" path="orderProductPrice" class="form-item">
                    <n-input-number v-model:value="orderForm.orderProductPrice" placeholder="请输入商品单价" :min="0"
                      :precision="2" class="modern-input" disabled @update:value="updateTotalAmount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>

                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">订单信息</h4>
                <div class="form-row">

                  <n-form-item label="订单号" path="orderId" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderId" placeholder="订单号自动生成无需输入" class="modern-input"
                      :disabled="true" />
                  </n-form-item>

                  <n-form-item label="订单名称" path="orderName" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderName" placeholder="订单名称自动生成无需输入" class="modern-input"
                      :disabled="true" />
                  </n-form-item>
                </div>

                <div class="form-row">
                  <n-form-item label="订单描述" path="orderDes" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderDes" placeholder="请输入订单描述信息" class="modern-input"
                      :disabled="modalMode === 'view'" />
                  </n-form-item>

                  <n-form-item label="订单口令" path="orderCommand" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderCommand" placeholder="请输入订单口令" class="modern-input"
                      :disabled="modalMode === 'view'" />
                  </n-form-item>
                </div>

                <div class="form-row">
                  <n-form-item label="数量" path="orderTotal" class="form-item">
                    <n-input-number v-model:value="orderForm.orderTotal" placeholder="请输入数量" :min="1"
                      class="modern-input" :disabled="modalMode === 'view'" @update:value="updateTotalAmount" />
                  </n-form-item>

                  <n-form-item label="总金额" path="orderSum" class="form-item">
                    <n-input-number v-model:value="orderForm.orderSum" placeholder="总金额" :precision="2" disabled
                      class="modern-input total-amount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>
                </div>

                <div class="form-row">

                  <n-form-item label="订单状态" path="orderType" class="form-item">
                    <n-select v-model:value="orderForm.orderType" placeholder="请选择订单状态" :options="currentStatusOptions"
                      class="modern-select" :disabled="modalMode === 'view'" />
                  </n-form-item>
                </div>

                <!-- <div class="form-row">
                  <n-form-item label="单价" path="price" class="form-item">
                    <n-input-number v-model:value="orderForm.price" placeholder="请输入单价" :min="0" :precision="2"
                      class="modern-input" :disabled="modalMode === 'view'" @update:value="updateTotalAmount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="总金额" path="totalAmount" class="form-item">
                    <n-input-number v-model:value="orderForm.totalAmount" placeholder="总金额" :precision="2" disabled
                      class="modern-input total-amount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>
                  <n-form-item label="订单状态" path="status" class="form-item">
                    <n-select v-model:value="orderForm.status" placeholder="请选择订单状态" :options="statusOptions"
                      class="modern-select" :disabled="modalMode === 'view'" />
                  </n-form-item>
                </div> -->

              </div>

              <div class="form-section">
                <h4 class="section-title">备注信息</h4>
                <n-form-item path="orderByUserOtherInfo" class="form-item full-width">
                  <n-input v-model:value="orderForm.orderByUserOtherInfo" type="textarea" placeholder="请输入备注信息,如客户商品链接"
                    :rows="3" class="modern-textarea" :disabled="modalMode === 'view'" />
                </n-form-item>
              </div>

            </div>
          </n-form>
        </div>
      </template>


      <template #action>
        <div class="modal-actions">
          <n-space v-if="modalMode !== 'view'" size="medium">
            <n-button @click="cancelOrderModal" class="cancel-btn">取消</n-button>
            <n-button type="primary" @click="confirmOrderModal('add')" :loading="submitLoading" class="confirm-btn">
              <template #icon>
                <n-icon>
                  <AddOutline v-if="modalMode === 'add'" />
                  <CreateOutline v-else />
                </n-icon>
              </template>
              {{ modalMode === 'add' ? '新增订单' : '保存修改' }}
            </n-button>
          </n-space>
          <n-space v-else size="medium">
            <n-button @click="cancelOrderModal" class="cancel-btn">
              关闭
            </n-button>
            <n-button type="primary" @click="switchToEditMode" class="confirm-btn">
              <template #icon>
                <n-icon>
                  <CreateOutline />
                </n-icon>
              </template>
              编辑订单
            </n-button>
          </n-space>
        </div>
      </template>
    </n-modal>

    <!-- 查看订单弹窗 -->
    <n-modal v-model:show="showViewModal" :mask-closable="false" preset="card" title="查看订单" class="modern-modal"
      :style="{ width: '800px' }" :auto-focus="false" :close-on-esc="false" transform-origin="center">
      <template #header>
        <div class="modal-header">
          <div class="modal-title-wrapper">
            <n-icon size="24" class="modal-icon">
              <EyeOutline />
            </n-icon>
            <div class="modal-title-text">
              <h3>查看订单</h3>
              <p class="modal-subtitle">查看订单详情</p>
            </div>
          </div>
        </div>
      </template>

      <template #default>
        <div class="modal-content">
          <n-form ref="orderFormRef" :model="orderForm" :rules="orderFormRules" label-placement="top"
            class="modern-form" disabled>
            <div class="form-grid">
              <div class="form-section">
                <h4 class="section-title">客户信息</h4>
                <div class="form-row">
                  <n-form-item label="客户ID" path="orderByUser" class="form-item">
                    <n-input v-model:value="orderForm.orderByUser" placeholder="请输入下单人ID" class="modern-input"
                      disabled />
                  </n-form-item>
                  <n-form-item label="客户账号" path="orderByUserName" class="form-item">
                    <n-input v-model:value="orderForm.orderByUserName" placeholder="请输下单人账号" class="modern-input"
                      disabled />
                  </n-form-item>
                  <n-form-item label="客户电话" path="orderByUserTel" class="form-item">
                    <n-input v-model:value="orderForm.orderByUserTel" placeholder="请输入下单人电话" class="modern-input"
                      disabled />
                  </n-form-item>
                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">商品信息</h4>
                <div class="form-row">
                  <n-form-item label="商品ID" path="orderProductId" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderProductId" placeholder="请输入商品ID" class="modern-input"
                      disabled />
                  </n-form-item>
                  <n-form-item label="商品名称" path="orderName" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderName" placeholder="请输入商品名称" class="modern-input" disabled />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="商品图片链接" path="orderProductImg" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderProductImg" placeholder="请输入商品图片链接" class="modern-input"
                      disabled />
                  </n-form-item>
                  <n-form-item label="商品单价" path="orderProductPrice" class="form-item">
                    <n-input-number v-model:value="orderForm.orderProductPrice" placeholder="请输入商品单价" :min="0"
                      :precision="2" class="modern-input" disabled>
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>
                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">订单信息</h4>
                <div class="form-row">
                  <n-form-item label="订单号" path="orderId" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderId" placeholder="订单号" class="modern-input" disabled />
                  </n-form-item>
                  <n-form-item label="订单名称" path="orderName" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderName" placeholder="订单名称" class="modern-input" disabled />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="订单描述" path="orderDes" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderDes" placeholder="订单描述" class="modern-input" disabled />
                  </n-form-item>
                  <n-form-item label="订单口令" path="orderCommand" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderCommand" placeholder="订单口令" class="modern-input" disabled />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="数量" path="orderTotal" class="form-item">
                    <n-input-number v-model:value="orderForm.orderTotal" placeholder="数量" :min="1" class="modern-input"
                      disabled />
                  </n-form-item>
                  <n-form-item label="总金额" path="orderSum" class="form-item">
                    <n-input-number v-model:value="orderForm.orderSum" placeholder="总金额" :precision="2" disabled
                      class="modern-input total-amount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="订单状态" path="orderType" class="form-item">
                    <n-select v-model:value="orderForm.orderType" placeholder="订单状态" :options="statusOptions"
                      class="modern-select" disabled />
                  </n-form-item>
                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">备注信息</h4>
                <n-form-item path="orderByUserOtherInfo" class="form-item full-width">
                  <n-input v-model:value="orderForm.orderByUserOtherInfo" type="textarea" placeholder="备注信息" :rows="3"
                    class="modern-textarea" disabled />
                </n-form-item>
              </div>
            </div>
          </n-form>
        </div>
      </template>

      <template #action>
        <div class="modal-actions">
          <n-space size="medium">
            <n-button @click="cancelViewModal" class="cancel-btn">
              关闭
            </n-button>
            <!-- <n-button type="primary" @click="switchToEditMode" class="confirm-btn">
              <template #icon>
                <n-icon><CreateOutline /></n-icon>
              </template>
  编辑订单
  </n-button> -->
          </n-space>
        </div>
      </template>
    </n-modal>

    <!-- 编辑订单弹窗 -->
    <n-modal v-model:show="showEditModal" :mask-closable="false" preset="card" title="编辑订单" class="modern-modal"
      :style="{ width: '800px' }" :auto-focus="false" :close-on-esc="false" transform-origin="center">
      <template #header>
        <div class="modal-header">
          <div class="modal-title-wrapper">
            <n-icon size="24" class="modal-icon">
              <CreateOutline />
            </n-icon>
            <div class="modal-title-text">
              <h3>编辑订单</h3>
              <p class="modal-subtitle">修改订单信息</p>
            </div>
          </div>
        </div>
      </template>

      <template #default>
        <div class="modal-content">
          <n-form ref="orderFormRef" :model="orderForm" :rules="orderFormRules" label-placement="top"
            class="modern-form">
            <div class="form-grid">
              <div class="form-section">
                <h4 class="section-title">客户信息</h4>
                <div class="form-row">
                  <n-form-item label="客户ID" path="orderByUser" class="form-item">
                    <n-input v-model:value="orderForm.orderByUser" placeholder="请输入下单人ID" class="modern-input"
                      @blur="getUserInfoById" />
                  </n-form-item>
                  <n-form-item label="客户账号" path="orderByUserName" class="form-item">
                    <n-input v-model:value="orderForm.orderByUserName" placeholder="请输下单人账号" class="modern-input"
                      @blur="getUserInfoById" />
                  </n-form-item>
                  <n-form-item label="客户电话" path="orderByUserTel" class="form-item">
                    <n-input v-model:value="orderForm.orderByUserTel" placeholder="请输入下单人电话" class="modern-input"
                      disabled />
                  </n-form-item>
                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">商品信息</h4>
                <div class="form-row">
                  <n-form-item label="商品ID" path="orderProductId" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderProductId" placeholder="请输入商品ID" class="modern-input"
                      @blur="getProductById" />
                  </n-form-item>
                  <n-form-item label="商品名称" path="orderName" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderName" placeholder="请输入商品名称" class="modern-input"
                      @blur="getProductById" />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="商品图片链接" path="orderProductImg" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderProductImg" placeholder="请输入商品图片链接" class="modern-input"
                      disabled />
                  </n-form-item>
                  <n-form-item label="商品单价" path="orderProductPrice" class="form-item">
                    <n-input-number v-model:value="orderForm.orderProductPrice" placeholder="请输入商品单价" :min="0"
                      :precision="2" class="modern-input" disabled @update:value="updateTotalAmount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>
                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">订单信息</h4>
                <div class="form-row">
                  <n-form-item label="订单号" path="orderId" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderId" placeholder="订单号" class="modern-input" disabled />
                  </n-form-item>
                  <n-form-item label="订单名称" path="orderName" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderName" placeholder="订单名称" class="modern-input" disabled />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="订单描述" path="orderDes" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderDes" placeholder="请输入订单描述信息" class="modern-input" />
                  </n-form-item>
                  <n-form-item label="订单口令" path="orderCommand" class="form-item full-width">
                    <n-input v-model:value="orderForm.orderCommand" placeholder="请输入订单口令" class="modern-input" />
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="数量" path="orderTotal" class="form-item">
                    <n-input-number v-model:value="orderForm.orderTotal" placeholder="请输入数量" :min="1"
                      class="modern-input" @update:value="updateTotalAmount" />
                  </n-form-item>
                  <n-form-item label="总金额" path="orderSum" class="form-item">
                    <n-input-number v-model:value="orderForm.orderSum" placeholder="总金额" :precision="2" disabled
                      class="modern-input total-amount">
                      <template #prefix>¥</template>
                    </n-input-number>
                  </n-form-item>
                </div>
                <div class="form-row">
                  <n-form-item label="订单状态" path="orderType" class="form-item">
                    <n-select v-model:value="orderForm.orderType" placeholder="请选择订单状态" :options="currentStatusOptions"
                      class="modern-select" />
                  </n-form-item>
                </div>
              </div>

              <div class="form-section">
                <h4 class="section-title">备注信息</h4>
                <n-form-item path="orderByUserOtherInfo" class="form-item full-width">
                  <n-input v-model:value="orderForm.orderByUserOtherInfo" type="textarea" placeholder="请输入备注信息,如客户商品链接"
                    :rows="3" class="modern-textarea" />
                </n-form-item>
              </div>
            </div>
          </n-form>
        </div>
      </template>

      <template #action>
        <div class="modal-actions">
          <n-space size="medium">
            <n-button @click="cancelEditModal" class="cancel-btn">
              取消
            </n-button>
            <n-button type="primary" @click="confirmOrderModal('edit')" :loading="submitLoading" class="confirm-btn">
              <template #icon>
                <n-icon>
                  <CreateOutline />
                </n-icon>
              </template>
              保存修改
            </n-button>
          </n-space>
        </div>
      </template>
    </n-modal>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import { useMessage, useDialog, FormInst, FormRules } from 'naive-ui'
import { NButton, NTag, NImage, NSwitch } from 'naive-ui'
import {
  SearchOutline,
  RefreshOutline,
  AddOutline,
  DownloadOutline,
  CreateOutline,
  TrashOutline,
  EyeOutline
} from '@vicons/ionicons5'
import PageLayout from '@/components/PageLayout.vue'
import { v4 as uuidv4 } from 'uuid';

import { orderAPI } from '@/api/order'
import { loginAPI } from '@/api/login'

// 添加组件名称
defineOptions({
  name: 'OrderManagement'
})

const message = useMessage()
const dialog = useDialog()
const loading = ref(false)

// 行选中相关
const checkedRowKeys = ref<string[]>([])
const selectedRows = ref<any[]>([])

// 处理行选中变化
const handleCheckedRowKeysChange = (keys: string[]) => {
  checkedRowKeys.value = keys
  selectedRows.value = tableData.value.filter(item => keys.includes(item.orderId))
}

// 获取行类名
const getRowClassName = (row: any) => {
  if (checkedRowKeys.value.includes(row.orderId)) {
    return 'rainbow-selected-row'
  }
  return ''
}

// 处理行点击事件
const handleRowClick = (row: any, index: number) => {
  const rowKey = row.orderId
  const currentIndex = checkedRowKeys.value.indexOf(rowKey)

  if (currentIndex > -1) {
    // 如果当前行已选中，则取消选中
    checkedRowKeys.value.splice(currentIndex, 1)
  } else {
    // 如果当前行未选中，则选中
    checkedRowKeys.value.push(rowKey)
  }

  // 更新选中的行数据
  selectedRows.value = tableData.value.filter(item => checkedRowKeys.value.includes(item.orderId))

  // 打印日志方便调试
  console.log('点击行:', row.orderId, '当前选中:', checkedRowKeys.value)
}

const getDataParam = reactive({
  orderId: '', // 订单号
  orderName: '', // 订单名称
  orderProductId: '', // 订单商品ID
  orderDes: '', // 订单描述
  orderProductPrice: '', // 订单商品单价
  orderSum: '', // 订单总价
  orderTotal: '', // 下单数
  orderProductImg: '', // 商品图片链接
  orderType: '', // 订单状态
  orderByUser: '', // 下单人ID
  orderByUserName: '', // 下单人姓名
  orderByUserTel: '', // 下单人电话
  orderByUserOtherInfo: '', // 订单附加信息
  orderCommand: '', // 订单口令
  OrderCreateTime: '', // 下单时间
  orderOperateTm: '', // 订单处理完成时间
  pageSize: 10, // 每页条数
  currentPage: 1, // 当前页数
})

// 弹窗相关
const showOrderModal = ref(false) // 新增弹窗
const showViewModal = ref(false) // 查看弹窗
const showEditModal = ref(false) // 编辑弹窗

const modalMode = ref<'add' | 'edit' | 'view'>('add')
const modalTitle = computed(() => {
  const titles = {
    add: '新增订单',
    edit: '编辑订单',
    view: '查看订单'
  }
  return titles[modalMode.value]
})
const submitLoading = ref(false)
const orderFormRef = ref<FormInst | null>(null)

// 订单表单
const orderForm = ref({
  orderId: '', // 订单号
  orderName: '', // 订单名称
  orderProductId: '', // 订单商品ID
  orderProductName: '', // 商品名称
  orderDes: '', // 订单描述
  orderProductPrice: 0, // 订单单价  订单商品单价
  orderSum: 0, // 订单总价
  orderTotal: 1, // 订单下单个数  下单数
  orderProductImg: '', // 订单商品图片链接    商品图片链接
  orderType: null,// 订单处理类型 0待处理/1处理中/2处理完成   订单状态
  orderByUser: '', // 订单下单人ID  下单人ID
  orderByUserName: '', // 订单下单人   下单人姓名
  orderByUserTel: '', // 订单下单人电话    下单人电话
  orderByUserOtherInfo: '', // 订单附加信息
  orderCommand: '', // 订单口令
  OrderCreateTime: '', // 订单创建时间    下单时间
  orderOperateTm: '', // 订单处理完成时间
})

// 表单验证规则
const orderFormRules: FormRules = {
  // 客户ID
  orderByUser: [
    { required: true, message: '请输入客户ID', trigger: 'blur' }
  ],
  // 客户账号
  orderByUserName: [
    { required: true, message: '请输入客户账号', trigger: 'blur' }
  ],
  // 商品ID
  orderProductId: [
    { required: true, message: '请输入商品ID', trigger: 'blur' }
  ],
  // 商品名称
  orderProductName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  // 数量
  // orderTotal: [
  //   { required: true, message: '请输入数量', trigger: 'blur' },
  //   // { validator: (rule: any, value: number) => value >= 1, message: '数量必须大于0', trigger: 'blur' }
  // ],
  // 订单状态
  // orderType: [
  //   { required: true, message: '请选择订单状态', trigger: 'blur' }
  // ],
  // 备注信息
  orderByUserOtherInfo: [
    { required: true, message: '请输入备注信息', trigger: 'blur' }
  ],


  // orderNumber: [
  //   { required: true, message: '请输入订单号', trigger: 'blur' }
  // ],
  // customerName: [
  //   { required: true, message: '请输入客户姓名', trigger: 'blur' }
  // ],
  // productName: [
  //   { required: true, message: '请输入商品名称', trigger: 'blur' }
  // ],
  // quantity: [
  //   { required: true, message: '请输入数量', trigger: 'blur' },
  //   { validator: (rule: any, value: number) => value >= 1, message: '数量必须大于0', trigger: 'blur' }
  // ],
  // price: [
  //   { required: true, message: '请输入单价', trigger: 'blur' },
  //   { validator: (rule: any, value: number) => value >= 0, message: '单价不能小于0', trigger: 'blur' }
  // ],
  // status: [
  //   { required: true, message: '请选择订单状态', trigger: 'change' }
  // ]
}

// 搜索表单
const searchForm = ref({
  orderId: '', // 订单号
  orderName: '', // 订单名称
  orderProductId: '', // 订单商品ID
  orderDes: '', // 订单描述
  orderProductPrice: '', // 订单单价  订单商品单价
  orderSum: '', // 订单总价
  orderTotal: '', // 订单下单个数  下单数
  orderProductImg: '', // 订单商品图片链接    商品图片链接
  orderType: null,// 订单处理类型 0待处理/1处理中/2处理完成   订单状态
  orderByUser: '', // 订单下单人ID  下单人ID
  orderByUserName: '', // 订单下单人   下单人姓名
  orderByUserTel: '', // 订单下单人电话    下单人电话
  orderByUserOtherInfo: '', // 订单附加信息
  orderCommand: '', // 订单口令
  OrderCreateTime: '', // 订单创建时间    下单时间
  orderOperateTm: '', // 订单处理完成时间
})

// 状态选项 - 修改为数字状态值
const statusOptions = [
  { label: '待处理', value: 0 },
  { label: '处理中', value: 1 },
  { label: '已完成', value: 2 },
  { label: '已取消', value: 3 },
  { label: '已删除', value: 4 },
]

// 根据模式动态获取状态选项
const currentStatusOptions = computed(() => {
  if (modalMode.value === 'add') {
    // 新增时只显示待处理选项
    return [{ label: '待处理', value: 0 }]
  } else if (modalMode.value === 'edit') {
    // 编辑时显示除了"已删除"之外的所有选项
    return statusOptions.filter(option => option.value !== 4)
  } else {
    // 查看时显示全部选项
    return statusOptions
  }
})

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

const UUID = () => {
  return uuidv4().replace(/-/g, '').substring(0, 32)
}

// 通过商品ID 或者商品名字  获取商品信息
const getProductById = async () => {
  console.log("getProductByIdgetProductByIdgetProductById", orderForm.value.orderProductId)
  if (orderForm.value.orderProductId !== '' || orderForm.value.orderProductName !== '') {
    const res = await orderAPI.getProductInfoById({
      id: orderForm.value.orderProductId,
      product_name: orderForm.value.orderProductName.replace("购买: ", ''),
    })
    console.log('✅ 根据商品ID查询商品信息:', res)
    if (res.code === 200 && res.msg === '查询商品信息成功') {
      orderForm.value.orderProductId = res.data.id
      orderForm.value.orderProductImg = res.data.product_img_url
      orderForm.value.orderProductPrice = res.data.product_price
      orderForm.value.orderName = "购买: " + res.data.product_name
      orderForm.value.orderProductName = res.data.product_name
    } else {
      orderForm.value.orderProductName = ''
      orderForm.value.orderProductId = ''
      message.warning('商品不存在')

    }
  }

}

// 通过用户ID 或者 账号名 或者 用户电话 获取用户信息
const getUserInfoById = async () => {
  console.log("getUserInfoByIdgetUserInfoByIdgetUserInfoByIdgetUserInfoById")
  if (
    orderForm.value.orderByUser !== '' ||
    orderForm.value.orderByUserName !== '' ||
    orderForm.value.orderByUserTel !== ''
  ) {
    const res = await orderAPI.getUserInfoByIdOrNameOrTel({
      usrId: orderForm.value.orderByUser,
      uName: orderForm.value.orderByUserName,
      uCellphone: orderForm.value.orderByUserTel,
    })
    console.log('✅ 通过用户ID 或者 账号名 或者 用户电话 获取用户信息:', res)
    if (res.code === 200 && res.msg === '用户信息查询成功') {
      orderForm.value.orderByUser = res.data.usrId
      orderForm.value.orderByUserName = res.data.uName
      orderForm.value.orderByUserTel = res.data.uCellphone
    } else {
      orderForm.value.orderByUser = ''
      orderForm.value.orderByUserName = ''
      orderForm.value.orderByUserTel = ''
      message.warning('未查询到用户信息')

    }
  }

}

// 处理订单开关切换
const handleProcessSwitch = async (row: any, value: boolean) => {
  try {
    // 确定新状态：开启为处理中(1)，关闭为待处理(0)
    const newStatus = value ? 1 : 0

    // 更新本地数据
    const index = allData.value.findIndex(item => item.orderId === row.orderId)
    if (index !== -1) {
      allData.value[index].orderType = newStatus

      // 更新当前页面显示的数据
      const currentIndex = tableData.value.findIndex(item => item.orderId === row.orderId)
      if (currentIndex !== -1) {
        tableData.value[currentIndex].orderType = newStatus
      }
    }

    // 这里可以添加API调用来更新后端状态
    console.log({ orderId: row.orderId, orderType: newStatus })
    const res = await orderAPI.updateOrderType({ orderId: row.orderId, orderType: newStatus })

    console.log(res)
    if (res.code === 200 && res.msg === '订单状态更新成功') {
      const statusText = value ? '处理中' : '待处理'
      message.success(`订单  ${row.orderId}  状态已更新为：${statusText}`)
      getOrderList(null) // 重新加载数据
    }



  } catch (error) {
    console.error('更新订单状态失败:', error)
    message.error('更新订单状态失败')

    // 如果更新失败，恢复原状态
    getOrderList(null)
  }
}



// 分页前缀
const paginationPrefix = ({ itemCount }: any) => `共 ${itemCount} 条数据`

// 表格列配置
const columns: any[] = [
  // 选择列
  {
    type: 'selection',
    width: 50,
    fixed: 'left'
  },
  // 订单号 - 左侧固定
  {
    title: '订单号',
    key: 'orderId',
    width: 120,
    filterable: true,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', {
      class: 'order-number',
      style: { fontWeight: '600', color: '#1890ff' }
    }, row.orderId || 'N/A')
  },

  // 商品名称
  {
    title: '订单名称',
    key: 'orderName',
    width: 150,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.orderName || '未知商品')
  },


  // 商品图片链接
  // {
  //   title: '商品图片链接',
  //   key: 'orderProductImg',
  //   width: 180,
  //   ellipsis: {
  //     tooltip: true
  //   },
  //   render: (row: any) => h('span', null, row.orderProductImg || '')
  // },

  {
    title: '商品图片',
    key: 'orderProductImg',
    width: 120,
    render: (row: any) => {
      if (row.orderProductImg) {
        return h(NImage, {
          width: 60,
          height: 60,
          src: row.orderProductImg,
          objectFit: 'cover',
          previewDisabled: false,
          style: 'border-radius: 6px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);'
        })
      }
    }
  },


  // 客户姓名
  {
    title: '客户姓名',
    key: 'orderByUserName',
    width: 120,
    render: (row: any) => h('span', null, row.orderByUserName || '未知客户')
  },

  // 客户电话
  {
    title: '客户电话',
    key: 'orderByUserTel',
    width: 130,
    render: (row: any) => h('span', {
      style: { fontFamily: 'Monaco, Consolas, monospace', fontSize: '13px' }
    }, row.orderByUserTel || '无电话')
  },

  // 数量
  {
    title: '数量',
    key: 'orderTotal',
    width: 80,
    align: 'center',
    render: (row: any) => h('span', {
      class: 'quantity-badge',
      style: {
        color: '#52c41a',
        fontWeight: '600',
        background: '#f6ffed',
        padding: '2px 8px',
        borderRadius: '4px',
        border: '1px solid #b7eb8f'
      }
    }, `${row.orderTotal || 0}`),
    sorter: (row1: any, row2: any) => (row1.orderTotal || 0) - (row2.orderTotal || 0)
  },

  // 单价
  {
    title: '单价',
    key: 'orderProductPrice',
    width: 100,
    align: 'right',
    render: (row: any) => h('span', {
      class: 'unit-price',
      style: { fontWeight: '600', color: '#fa541c' }
    }, `¥${(row.orderProductPrice || 0).toFixed(2)}`),
    sorter: (row1: any, row2: any) => (row1.orderProductPrice || 0) - (row2.orderProductPrice || 0)
  },

  // 总价
  {
    title: '总价',
    key: 'orderSum',
    width: 120,
    align: 'right',
    render: (row: any) => h('span', {
      class: 'total-price',
      style: { fontWeight: '700', fontSize: '16px', color: '#f5222d' }
    }, `¥${(row.orderSum || 0).toFixed(2)}`),
    sorter: (row1: any, row2: any) => (row1.orderSum || 0) - (row2.orderSum || 0)
  },

  // 订单状态
  {
    title: '状态',
    key: 'orderType',
    width: 100,
    align: 'center',
    render: (row: any) => {
      // 数字状态映射 - 根据API返回的数字状态
      const statusMap: Record<number, { type: string; label: string }> = {
        0: { type: 'warning', label: '待处理' },
        1: { type: 'info', label: '处理中' },
        2: { type: 'success', label: '已完成' },
        3: { type: 'error', label: '已取消' },
        4: { type: 'error', label: '已删除' }
      }
      const status = statusMap[row.orderType] || { type: 'default', label: '未知状态' }
      return h(NTag, {
        type: status.type as any,
        size: 'small',
        round: true
      }, { default: () => status.label })
    },
    filterable: true,
    filterOptions: [
      { label: '待处理', value: 0 },
      { label: '处理中', value: 1 },
      { label: '已完成', value: 2 },
      { label: '已取消', value: 3 },
      { label: '已删除', value: 4 }
    ],
    filter: (value: any, row: any) => row.orderType === value
  },

  // 订单处理开关
  {
    title: '处理开关',
    key: 'processSwitch',
    width: 90,
    align: 'center',
    render: (row: any) => {
      // 只有待处理(0)和处理中(1)状态才能操作开关
      const canOperate = row.orderType === 0 || row.orderType === 1

      return h(NSwitch, {
        value: row.orderType === 1, // 处理中状态为开启
        disabled: !canOperate,
        size: 'small',
        onUpdateValue: (value: boolean) => handleProcessSwitch(row, value)
      })
    }
  },

  // 订单附加信息
  {
    title: '订单附加信息',
    key: 'orderByUserOtherInfo',
    width: 300,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.orderByUserOtherInfo || '')
  },

  // 下单用户ID
  {
    title: '下单用户ID',
    key: 'orderByUser',
    width: 180,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.orderByUser || '')
  },


  // 商品名称
  {
    title: '订单商品ID',
    key: 'orderProductId',
    width: 260,
    // ellipsis: {
    //   tooltip: true
    // },
    render: (row: any) => h('span', null, row.orderProductId || '')
  },

  // 订单描述
  {
    title: '订单描述',
    key: 'orderDes',
    width: 180,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.orderDes || '')
  },


  // 订单口令
  {
    title: '订单口令',
    key: 'orderCommand',
    width: 120,
    render: (row: any) => h('span', null, row.orderCommand || '')
  },

  // 下单时间
  {
    title: '下单时间',
    key: 'orderCreateTime',
    width: 300,
    render: (row: any) => {
      if (!row.orderCreateTime) {
        return h('div', { class: 'time-cell' }, [
          h('div', { class: 'time-date' }, '未知日期'),
          h('div', { class: 'time-time' }, '未知时间')
        ])
      }

      const date = new Date(row.orderCreateTime)
      const dateStr = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
      const timeStr = date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })

      return h('div', { class: 'time-cell' }, [
        h('div', { class: 'time-date' }, dateStr),
        h('div', { class: 'time-time' }, timeStr)
      ])
    },
    sorter: (row1: any, row2: any) => {
      const time1 = row1.orderCreateTime ? new Date(row1.orderCreateTime).getTime() : 0
      const time2 = row2.orderCreateTime ? new Date(row2.orderCreateTime).getTime() : 0
      return time1 - time2
    }
  },

  // 订单处理时间
  {
    title: '订单处理时间',
    key: 'orderOperateTm',
    width: 300,
    render: (row: any) => {
      if (!row.orderOperateTm) {
        return h('div', { class: 'time-cell' }, [
          h('div', { class: 'time-date' }, ''),
          h('div', { class: 'time-time' }, '')
        ])
      }

      const date = new Date(row.orderOperateTm)
      const dateStr = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
      const timeStr = date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })

      return h('div', { class: 'time-cell' }, [
        h('div', { class: 'time-date' }, dateStr),
        h('div', { class: 'time-time' }, timeStr)
      ])
    },
    sorter: (row1: any, row2: any) => {
      const time1 = row1.orderOperateTm ? new Date(row1.orderOperateTm).getTime() : 0
      const time2 = row2.orderOperateTm ? new Date(row2.orderOperateTm).getTime() : 0
      return time1 - time2
    }
  },

  // 操作按钮 - 右侧固定
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    fixed: 'right',
    render: (row: any) => {
      const buttons = []

      // 所有状态都有查看按钮
      buttons.push(h(NButton, {
        size: 'small',
        type: 'info',
        quaternary: true,
        onClick: () => handleView(row)
      }, { default: () => '查看' }))

      // 只有待处理(0)和处理中(1)状态才有编辑和删除按钮
      if (row.orderType === 0 || row.orderType === 1) {
        buttons.push(h(NButton, {
          size: 'small',
          type: 'info',
          quaternary: true,
          style: { marginLeft: '8px' },
          onClick: () => handleEdit(row)
        }, { default: () => '编辑' }))

        buttons.push(h(NButton, {
          size: 'small',
          type: 'error',
          quaternary: true,
          style: { marginLeft: '8px' },
          onClick: () => handleDelete(row)
        }, { default: () => '删除' }))
      }

      return h('div', { class: 'action-buttons' }, buttons)
    }
  }
]

// 表格数据
const tableData = ref<any[]>([])
const allData = ref<any[]>([])

// 获取列表信息
const getOrderList = async (params: any) => {
  try {
    loading.value = true

    // 使用最简单的参数进行测试
    const requestParams = {

      pageSize: pagination.value.pageSize, // 每页条数
      currentPage: pagination.value.page,  // 当前页码

      orderId: searchForm.value.orderId, // 订单号
      orderName: searchForm.value.orderName, // 订单名称
      orderProductId: searchForm.value.orderProductId, // 订单商品ID
      orderDes: searchForm.value.orderDes, // 订单描述
      orderProductPrice: searchForm.value.orderProductPrice, // 订单单价  订单商品单价
      orderSum: searchForm.value.orderSum, // 订单总价
      orderTotal: searchForm.value.orderTotal, // 订单下单个数  下单数
      orderProductImg: searchForm.value.orderProductImg, // 订单商品图片链接    商品图片链接
      orderType: searchForm.value.orderType,// 订单处理类型 0待处理/1处理中/2处理完成   订单状态
      orderByUser: searchForm.value.orderByUser, // 订单下单人ID  下单人ID
      orderByUserName: searchForm.value.orderByUserName, // 订单下单人   下单人姓名
      orderByUserTel: searchForm.value.orderByUserTel, // 订单下单人电话    下单人电话
      orderByUserOtherInfo: searchForm.value.orderByUserOtherInfo, // 订单附加信息
      orderCommand: searchForm.value.orderCommand, // 订单口令
      OrderCreateTime: searchForm.value.OrderCreateTime, // 订单创建时间    下单时间
      orderOperateTm: searchForm.value.orderOperateTm, // 订单处理完成时间
    }

    // console.log('📤 发送请求参数:', requestParams)

    try {
      // 使用 orderAPI 调用后端接口
      const res = await orderAPI.getList(requestParams)
      // console.log('✅ 订单API响应:', res)

      const listCount = await orderAPI.getListCount(requestParams)
      // console.log(listCount)

      if (res.code === 200) {
        // 处理新的响应格式
        if (res.data && typeof res.data === 'object') {
          // 如果是 OrderListResponse 格式
          if ('list' in res.data) {
            tableData.value = res.data.list || []
            allData.value = res.data.list || []
            pagination.value.itemCount = listCount.data || 0
          } else if (Array.isArray(res.data)) {
            // 如果直接是数组格式
            tableData.value = res.data
            allData.value = res.data
            pagination.value.itemCount = listCount.data
          } else {
            // 其他格式
            tableData.value = []
            allData.value = []
            pagination.value.itemCount = 0
          }
        } else {
          tableData.value = []
          allData.value = []
          pagination.value.itemCount = 0
        }
        // message.success('获取订单列表成功')
      } else {
        console.error('❌ API返回错误:', res)
        message.error(res.msg || res.message || '获取订单列表失败')
        // 清空数据
        tableData.value = []
        allData.value = []
        pagination.value.itemCount = 0
      }

    } catch (apiError: any) {
      console.error('❌ API调用异常:', apiError)
      message.error(`连接后端失败: ${apiError.message || '网络错误'}`)
      // 清空数据
      tableData.value = []
      allData.value = []
      pagination.value.itemCount = 0
    }

  } catch (error: any) {
    console.error('❌ 获取订单失败:', error)
    message.error('获取订单列表失败: ' + (error.message || '网络错误'))
    // 清空数据
    tableData.value = []
    allData.value = []
    pagination.value.itemCount = 0
  } finally {
    loading.value = false
  }
}

// 事件处理
const handleSearch = () => {
  pagination.value.page = 1 // 重置到第一页
  getOrderList(searchForm) // 获取订单列表
}

const handleReset = () => {
  searchForm.value = {
    orderId: '', // 订单号
    orderName: '', // 订单名称
    orderProductId: '', // 订单商品ID
    orderDes: '', // 订单描述
    orderProductPrice: '', // 订单单价  订单商品单价
    orderSum: '', // 订单总价
    orderTotal: '', // 订单下单个数  下单数
    orderProductImg: '', // 订单商品图片链接    商品图片链接
    orderType: null,// 订单处理类型 0待处理/1处理中/2处理完成   订单状态
    orderByUser: '', // 订单下单人ID  下单人ID
    orderByUserName: '', // 订单下单人   下单人姓名
    orderByUserTel: '', // 订单下单人电话    下单人电话
    orderByUserOtherInfo: '', // 订单附加信息
    orderCommand: '', // 订单口令
    OrderCreateTime: '', // 订单创建时间    下单时间
    orderOperateTm: '', // 订单处理完成时间
  }
  pagination.value.page = 1 // 重置到第一页
  getOrderList(null) // 重新加载数据
  message.info('已重置搜索条件')
}

const handleRefresh = () => {
  getOrderList(null) // 重新加载数据
  message.info('数据已刷新')
}

// 弹窗相关函数
const resetOrderForm = () => {
  orderForm.value = {
    orderId: orderForm.value.orderId, // 订单号
    orderName: '', // 订单名称
    orderProductId: '', // 订单商品ID
    orderProductName: '', // 商品名称
    orderDes: '', // 订单描述
    orderProductPrice: 0, // 订单单价  订单商品单价
    orderSum: 0, // 订单总价
    orderTotal: 1, // 订单下单个数  下单数
    orderProductImg: '', // 订单商品图片链接    商品图片链接
    orderType: null,// 订单处理类型 0待处理/1处理中/2处理完成   订单状态
    orderByUser: '', // 订单下单人ID  下单人ID
    orderByUserName: '', // 订单下单人   下单人姓名
    orderByUserTel: '', // 订单下单人电话    下单人电话
    orderByUserOtherInfo: '', // 订单附加信息
    orderCommand: '', // 订单口令
    OrderCreateTime: '', // 订单创建时间    下单时间
    orderOperateTm: '', // 订单处理完成时间
  }
}

const updateTotalAmount = () => {
  orderForm.value.orderSum = (orderForm.value.orderTotal || 0) * (orderForm.value.orderProductPrice || 0)
}

const handleAdd = () => {
  modalMode.value = 'add'
  resetOrderForm()
  showOrderModal.value = true
  // 生成订单号
  orderForm.value.orderId = UUID()
  // 新增模式下设置默认状态为待处理
  orderForm.value.orderType = 0
}

const handleView = (row: any) => {
  modalMode.value = 'view'
  console.log("查看数据", row)
  // 映射API数据到表单格式
  orderForm.value = {
    orderId: row.orderId || '',
    orderName: row.orderName || '',
    orderProductId: row.orderProductId || '',
    orderProductName: row.orderProductName || '',
    orderDes: row.orderDes || '',
    orderProductPrice: row.orderProductPrice || 0,
    orderSum: row.orderSum || 0,
    orderTotal: row.orderTotal || 1,
    orderProductImg: row.orderProductImg || '',
    orderType: row.orderType,
    orderByUser: row.orderByUser || '',
    orderByUserName: row.orderByUserName || '',
    orderByUserTel: row.orderByUserTel || '',
    orderByUserOtherInfo: row.orderByUserOtherInfo || '',
    orderCommand: row.orderCommand || '',
    OrderCreateTime: row.OrderCreateTime || '',
    orderOperateTm: row.orderOperateTm || '',
  }
  showViewModal.value = true
}

const handleEdit = (row: any) => {
  modalMode.value = 'edit'
  // 映射API数据到表单格式
  orderForm.value = {
    orderId: row.orderId || '',
    orderName: row.orderName || '',
    orderProductId: row.orderProductId || '',
    orderProductName: row.orderProductName || '',
    orderDes: row.orderDes || '',
    orderProductPrice: row.orderProductPrice || 0,
    orderSum: row.orderSum || 0,
    orderTotal: row.orderTotal || 1,
    orderProductImg: row.orderProductImg || '',
    orderType: row.orderType,
    orderByUser: row.orderByUser || '',
    orderByUserName: row.orderByUserName || '',
    orderByUserTel: row.orderByUserTel || '',
    orderByUserOtherInfo: row.orderByUserOtherInfo || '',
    orderCommand: row.orderCommand || '',
    OrderCreateTime: row.OrderCreateTime || '',
    orderOperateTm: row.orderOperateTm || '',
  }
  showEditModal.value = true
}

const cancelOrderModal = () => {
  showOrderModal.value = false
  resetOrderForm()
}

const cancelViewModal = () => {
  showViewModal.value = false
  resetOrderForm()
}

const cancelEditModal = () => {
  showEditModal.value = false
  resetOrderForm()
}

const switchToEditMode = () => {
  showViewModal.value = false
  showEditModal.value = true
}

const confirmOrderModal = async (type: string) => {
  console.log("表单保存 modalMode.value ", modalMode.value)
  console.log("表单保存123 type", type)
  if (!orderFormRef.value) return
  try {
    await orderFormRef.value.validate()
    submitLoading.value = true

    console.log("表单保存", type)

    // if (modalMode.value === 'add') {
    if (type === 'add') {
      console.log("创建订单", orderForm.value)
      const res = await orderAPI.orderCreateBak(orderForm.value)
      console.log("新增订单返回结果", res)
      if (res.code == 200 && res.msg === '订单创建失败' && res.data === '账户已冻结') {
        message.warning('账户已冻结，请联系管理员')
        submitLoading.value = false
        return
      }
      if (res.code == 200 && res.msg === '订单创建失败' && res.data === '余额不足') {
        message.warning('账户余额不足，请充值')
        submitLoading.value = false
        return
      }
      if (res.code == 200 && res.msg === '订单创建成功') {
        message.success('下单成功，请关注订单状态')
        submitLoading.value = false
      }

    }
    if (type === 'edit') {

      console.log("修改订单", orderForm.value)
      const res = await orderAPI.orderUpdateBak(orderForm.value)
      console.log("修改订单返回结果", res)

      if (res.code === 200 && res.data === '账户已冻结') {
        message.warning('订单修改失败 , 账户已冻结!')
        submitLoading.value = false
        showEditModal.value = false
        return
      }

      if (res.code === 200 && res.data === '账户余额不足') {
        message.warning('订单修改失败 , 账户余额不足!')
        submitLoading.value = false
        return
      }

      if (res.code === 200 && res.msg === '订单修改成功') {
        message.success('订单修改成功')
        submitLoading.value = false
        showEditModal.value = false
        resetOrderForm()   // 清空表单数据
        getOrderList(null) // 重新加载数据
        return
      }

      if (res.code === 200 && res.msg === '待处理-处理中-订单修改成功') {
        message.success('订单修改成功 , 订单状态更新为: 处理中')
        submitLoading.value = false
        showEditModal.value = false
        resetOrderForm()   // 清空表单数据
        getOrderList(null) // 重新加载数据
        return
      }

      if (res.code === 200 && res.msg === '订单金额已原路退回账户') {
        message.success('订单已取消 , 订单金额已原路退回账户!!')
        submitLoading.value = false
        showEditModal.value = false
        resetOrderForm()   // 清空表单数据
        getOrderList(null) // 重新加载数据
        return
      }

      if (res.code === 200 && res.msg === '处理中-待处理-订单修改成功') {
        message.success('订单修改成功 , 订单状态更新为: 待处理')
        submitLoading.value = false
        showEditModal.value = false
        resetOrderForm()   // 清空表单数据
        getOrderList(null) // 重新加载数据
        return
      }

      if (res.code === 200 && res.msg === '处理中-已完成-订单已完成') {
        message.success('订单修改成功 , 订单状态更新为: 已完成')
        submitLoading.value = false
        showEditModal.value = false
        resetOrderForm()   // 清空表单数据
        getOrderList(null) // 重新加载数据
        return
      }


    }


  } catch (error) {
    submitLoading.value = false
    message.error('保存失败，请联系管理员')
    console.error('保存失败:', error)
  }
}

// 保存编辑
const confirmEditModal = async () => {
  if (!orderFormRef.value) return

  try {
    await orderFormRef.value.validate()

    submitLoading.value = true

    // 在这里添加编辑订单的API调用
    console.log("confirmEditModal", orderForm.value)
    const res = await orderAPI.orderUpdateBak(orderForm.value)
    console.log("修改订单", res)

    message.success('编辑订单成功')

    submitLoading.value = false
    showEditModal.value = false
    resetOrderForm()

    // 刷新订单列表
    getOrderList(null)

  } catch (error) {
    console.error('表单验证失败:', error)
    submitLoading.value = false
  }
}


const deleteOrder = async (row: any) => {

  try {

    loading.value = true

    // 在这里添加编辑订单的API调用
    console.log("deleteOrder", row)
    const res = await orderAPI.deleteOrderByIdBak(row)
    console.log("删除订单", res)

    if (res.code === 200 && res.msg === '订单删除成功') {
      // 刷新订单列表
      getOrderList(null)
      loading.value = false
      message.success('删除订单成功，订单金额原路返回账户！')
    }



  } catch (error) {
    console.error('订单删除失败:', error)
    message.error('删除订单失败,请联系管理员')
    loading.value = false
  }
}



const handleDelete = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除订单 \n  ${row.orderId || row.orderNumber} 吗？\n 删除后金额原路返回账户！`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: () => {
      const index = allData.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        allData.value.splice(index, 1)
        pagination.value.itemCount = allData.value.length
        // 重新处理分页显示
        const startIndex = (pagination.value.page - 1) * pagination.value.pageSize
        const endIndex = startIndex + pagination.value.pageSize
        tableData.value = allData.value.slice(startIndex, endIndex)
        console.log("删除订单按钮", row)
        // loading.value = true // 表格loading
        deleteOrder(row) // 调用后台删除订单
        // message.success('删除订单成功')
      }
    }
  })
}

const handleExport = () => {
  message.info('导出数据功能')
}

const handlePageChange = (page: number) => {
  pagination.value.page = page
  getOrderList(null) // 重新加载数据
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  pagination.value.page = 1
  getOrderList(null) // 重新加载数据
}

const testAPI = async () => {
  try {
    console.log('🔍 开始测试API连接...')
    message.info('正在测试API连接...')

    // 最简单的测试参数
    const testParams = {
      pageSize: 10,
      currentPage: 1
    }

    console.log('📤 测试参数:', testParams)

    // 直接使用fetch测试，绕过axios
    const response = await fetch('/api/orderListBak', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(testParams)
    })

    console.log('📊 Fetch响应状态:', response.status)
    console.log('📊 Fetch响应头:', response.headers)

    if (response.ok) {
      const data = await response.json()
      console.log('📊 Fetch响应数据:', data)
      message.success('✅ API连接成功！')
    } else {
      const errorText = await response.text()
      console.error('❌ API响应错误:', errorText)
      message.error(`❌ API返回错误: ${response.status}`)
    }

  } catch (error) {
    console.error('❌ API测试失败:', error)
    message.error(`❌ 连接失败: ${error.message}`)
  }
}

onMounted(() => {
  // 页面加载时获取订单列表（如果API失败会自动加载模拟数据）
  getOrderList(null)
})
</script>

<style scoped>
.page-container {
  padding: var(--spacing-lg);
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-color-secondary);
}

.search-card {
  flex-shrink: 0;
  margin-bottom: var(--spacing-lg);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
}

.table-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-header-section {
  flex-shrink: 0;
  background: var(--bg-color-primary);
  border: 1px solid var(--border-color-primary);
  border-bottom: none;
  border-radius: 12px 12px 0 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color-primary);
}

.table-content {
  flex: 1;
  overflow: hidden;
  border-left: 1px solid var(--border-color-primary);
  border-right: 1px solid var(--border-color-primary);
  background: var(--bg-color-primary);
  min-height: 50%;
  max-height: 100%;
}

.table-data-area {
  flex: 1;
  overflow: auto;
  height: 100%;
  padding-bottom: 0px;
}

/* 🔧 表格基础样式 - 专业级滚动配置 */
.data-table {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 表格包装器 - 核心滚动配置 */
.data-table :deep(.n-data-table-wrapper) {
  border-radius: 8px;
  height: 100%;
}

/* 表格基础容器 */
.data-table :deep(.n-data-table) {
  height: 100%;
  /* 让Naive UI处理所有滚动逻辑 */
}

/* 表头样式 - 确保固定功能正常 */
.data-table :deep(.n-data-table-th) {
  background-color: #fafafa !important;
  font-weight: 600;
  font-size: 14px;
  color: #262626;
  border-bottom: 2px solid #e8e8e8;
  padding: 16px 12px;
  white-space: nowrap;
  position: sticky;
  top: 0;
  z-index: 10;
}

/* 表格单元格样式 */
.data-table :deep(.n-data-table-td) {
  padding: 12px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 15px;
  font-weight: 500;
  line-height: 1.6;
  letter-spacing: 0.3px;
  color: #2c3e50;
  border-bottom: 1px solid #f0f0f0;
  vertical-align: top;
  position: relative;
  z-index: 1;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

/* 固定列样式 - 确保固定列正常显示 */
.data-table :deep(.n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-td.n-data-table-td--fixed-right) {
  position: sticky !important;
  z-index: 10 !important;
  background: var(--n-td-color) !important;
}

/* 固定列在悬浮时的背景处理 */
.data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 固定列在选中时的背景处理 */
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 表格行悬停效果 - 动态渐变效果 */
.data-table :deep(.n-data-table-tr) {
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.data-table :deep(.n-data-table-tr:hover) {
  background-color: rgba(0, 0, 0, 0.02);
}

.data-table :deep(.n-data-table-tr:hover .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.2) 0%,
      rgba(255, 165, 0, 0.2) 12.5%,
      rgba(255, 255, 0, 0.2) 25%,
      rgba(0, 255, 0, 0.2) 37.5%,
      rgba(0, 255, 255, 0.2) 50%,
      rgba(0, 0, 255, 0.2) 62.5%,
      rgba(75, 0, 130, 0.2) 75%,
      rgba(238, 130, 238, 0.2) 87.5%,
      rgba(255, 0, 0, 0.2) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.1);
  z-index: 0;
}

.data-table :deep(.n-data-table-tr:hover .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

/* 选中行的彩虹色动态渐变效果 */
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.25) 0%,
      rgba(255, 165, 0, 0.25) 12.5%,
      rgba(255, 255, 0, 0.25) 25%,
      rgba(0, 255, 0, 0.25) 37.5%,
      rgba(0, 255, 255, 0.25) 50%,
      rgba(0, 0, 255, 0.25) 62.5%,
      rgba(75, 0, 130, 0.25) 75%,
      rgba(238, 130, 238, 0.25) 87.5%,
      rgba(255, 0, 0, 0.25) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.2);
  z-index: 0;
}

.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

@keyframes rainbowMove {
  0% {
    background-position: 0% 50%;
  }

  25% {
    background-position: 100% 50%;
  }

  50% {
    background-position: 200% 50%;
  }

  75% {
    background-position: 300% 50%;
  }

  100% {
    background-position: 400% 50%;
  }
}

/* 时间显示样式 */
.time-cell {
  line-height: 1.5;
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
}

.time-date {
  font-weight: 600;
  font-size: 14px;
  color: #1a202c;
  margin-bottom: 3px;
  letter-spacing: 0.2px;
}

.time-time {
  font-size: 13px;
  font-weight: 500;
  color: #4a5568;
  letter-spacing: 0.3px;
}

/* 深色模式时间显示样式 */
html.dark .time-date {
  color: #e2e8f0 !important;
}

html.dark .time-time {
  color: #a0aec0 !important;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.action-buttons .n-button {
  min-width: 50px;
  height: 28px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-buttons .n-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 🎯 响应式设计 */
@media (max-width: 1200px) {
  .order-info-card {
    max-width: 240px;
  }

  .customer-info-card,
  .price-info-card,
  .time-info-card {
    font-size: 13px;
  }
}

/* 🌙 深色模式适配 */
html.dark .data-table :deep(.n-data-table-th) {
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  color: #ecf0f1;
}

/* 深色模式表格行悬停效果 - 彩虹色动态渐变效果 */
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.3) 0%,
      rgba(255, 165, 0, 0.3) 12.5%,
      rgba(255, 255, 0, 0.3) 25%,
      rgba(0, 255, 0, 0.3) 37.5%,
      rgba(0, 255, 255, 0.3) 50%,
      rgba(0, 0, 255, 0.3) 62.5%,
      rgba(75, 0, 130, 0.3) 75%,
      rgba(238, 130, 238, 0.3) 87.5%,
      rgba(255, 0, 0, 0.3) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.3);
  z-index: 0;
}

html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

/* 深色模式选中行的彩虹色动态渐变效果 */
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.35) 0%,
      rgba(255, 165, 0, 0.35) 12.5%,
      rgba(255, 255, 0, 0.35) 25%,
      rgba(0, 255, 0, 0.35) 37.5%,
      rgba(0, 255, 255, 0.35) 50%,
      rgba(0, 0, 255, 0.35) 62.5%,
      rgba(75, 0, 130, 0.35) 75%,
      rgba(238, 130, 238, 0.35) 87.5%,
      rgba(255, 0, 0, 0.35) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.35);
  z-index: 0;
}

html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

html.dark .order-number {
  background: linear-gradient(135deg, #3498db, #5dade2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

html.dark .customer-avatar {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

/* 深色模式固定列样式 */
html.dark .data-table :deep(.n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-td.n-data-table-td--fixed-right) {
  position: sticky !important;
  z-index: 10 !important;
  background: var(--n-td-color) !important;
}

/* 深色模式固定列在悬浮时的背景处理 */
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 深色模式固定列在选中时的背景处理 */
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 深色模式表格单元格文字样式 */
html.dark .data-table :deep(.n-data-table-td) {
  color: #e8eaed !important;
  font-weight: 500;
}

/* 深色模式表格行悬停样式 */
html.dark .data-table :deep(.n-data-table-tr:hover) {
  background-color: rgba(255, 255, 255, 0.05) !important;
}

/* 数字类型文字样式 */
.data-table :deep(.n-data-table-td) .unit-price,
.data-table :deep(.n-data-table-td) .total-price,
.data-table :deep(.n-data-table-td) .quantity-badge {
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

/* 订单号样式 */
.data-table :deep(.n-data-table-td) .order-number {
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  font-weight: 700;
  font-size: 14px;
  letter-spacing: 0.5px;
}

/* 客户信息文字样式 */
.data-table :deep(.n-data-table-td) .customer-name,
.data-table :deep(.n-data-table-td) .product-name {
  font-weight: 600;
  font-size: 15px;
}

/* 状态标签文字样式 */
.data-table :deep(.n-data-table-td) .n-tag {
  font-weight: 600;
  font-size: 13px;
  letter-spacing: 0.2px;
}

/* 紧凑搜索表单样式 */
.compact-search-container {
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 8px 8px;
}

.compact-search-form {
  display: flex;
  align-items: center;
  gap: 0px;
  flex-wrap: wrap;
}

.compact-search-form .n-form-item {
  margin-bottom: 0 !important;
}

.compact-input {
  width: 200px;
}

.compact-select {
  width: 200px;
}

.compact-btn {
  height: 28px;
  border-radius: 6px;
  font-size: 12px;
  padding: 0 12px;
}

/* 现代化弹窗样式 */
.modern-modal {
  backdrop-filter: blur(10px);
}

.modern-modal :deep(.n-card) {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
}

.modal-header {
  padding: 24px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
}

.modal-title-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
}

.modal-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 8px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.modal-title-text h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.modal-subtitle {
  margin: 4px 0 0;
  font-size: 14px;
  color: #666;
  opacity: 0.8;
}

.modal-content {
  padding: 24px;
  max-height: 60vh;
  overflow-y: auto;
}

.form-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-section {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e8e8e8;
}

.section-title {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.form-row {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.form-item {
  flex: 1;
  min-width: 200px;
}

.form-item.full-width {
  width: 100%;
}

.modern-input :deep(.n-input) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
  background: white;
}

.modern-input :deep(.n-input:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.modern-input :deep(.n-input:focus-within) {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(64, 169, 255, 0.2);
}

.modern-select :deep(.n-base-selection) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.modern-select :deep(.n-base-selection:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.modern-textarea :deep(.n-input) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.modern-textarea :deep(.n-input:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.total-amount :deep(.n-input-number) {
  background: linear-gradient(135deg, #f6ffed 0%, #f6ffed 100%);
  border: 1px solid #b7eb8f;
}

.total-amount :deep(.n-input-number .n-input) {
  background: transparent;
  font-weight: 600;
  font-size: 16px;
  color: #52c41a;
}

.modal-actions {
  padding: 16px 24px 24px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  justify-content: flex-end;
}

.cancel-btn {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  border-color: #40a9ff;
  color: #40a9ff;
}

.confirm-btn {
  border-radius: 8px;
  background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
}

.confirm-btn:active {
  transform: translateY(0);
}

/* 弹窗动画效果 */
.modern-modal :deep(.n-modal) {
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(-20px);
  }

  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 紧凑表格头部样式 */
.compact-table-header {
  margin-bottom: 8px;
  display: flex;
  justify-content: flex-start;
  gap: 8px;
}

.compact-add-btn {
  height: 28px;
  padding: 0 12px;
  font-size: 12px;
  border-radius: 6px;
  margin-top: 10px;
  margin-left: 10px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .compact-search-form {
    flex-direction: column;
    gap: 8px;
  }

  .compact-input,
  .compact-select {
    width: 100%;
  }

  .form-row {
    flex-direction: column;
  }

  .form-item {
    min-width: 100%;
  }

  .modern-modal :deep(.n-card) {
    margin: 16px;
    width: calc(100% - 32px) !important;
  }
}

.pagination-section {
  flex-shrink: 0;
  padding: 8px 20px;
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
  background: var(--bg-color-primary);
  border: 1px solid var(--border-color-primary);
  border-top: none;
  border-radius: 0 0 12px 12px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 时间显示样式 */
.time-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.time-date {
  font-size: 13px;
  color: #1890ff;
  font-weight: 500;
}

.time-time {
  font-size: 12px;
  color: #666;
  font-family: Monaco, Consolas, monospace;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: var(--spacing-md);
  }

  .table-header {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }
}
</style>